package lysjmaster.base.common.spring.base;


import lombok.extern.slf4j.Slf4j;
import lysjmaster.base.common.exception.BaseException;
import lysjmaster.base.common.exception.ValidatorException;
import lysjmaster.base.common.web.ParamUtil;
import lysjmaster.base.common.web.Resp;
import lysjmaster.base.common.web.RespUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class BaseContent {

    @PersistenceContext
    public EntityManager em;


    @ExceptionHandler(ValidatorException.class)
    public Resp validationExHandle(ValidatorException e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        log.error(stackTraceElements[0] + "--" + e.toString());
        return RespUtil.error(Resp.ResStatus.PARAM_ERROR, e.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public Resp BaseExHandle(BaseException e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        log.error(stackTraceElements[0] + "--" + e.toString());
        return RespUtil.error(Resp.ResStatus.PARAM_ERROR, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Resp handleException(Exception e) {
        e.printStackTrace();
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        log.error(stackTraceElements[0] + "--" + e.toString());
        if (e instanceof BaseException) {
            BaseException myException = (BaseException) e;
            Resp resp = RespUtil.error(ParamUtil.isBlank(myException.getCode()) ? Resp.ResStatus.INNER_ERROR
                    : RespUtil.getStatusByCode(myException.getCode()), myException.getMessage());
            return resp;
        }
        return RespUtil.error(Resp.ResStatus.INNER_ERROR, e.getMessage() == null ? "oops" : e.getMessage());
    }

    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;

}
